import { defineStore } from 'pinia';
import { nextTick, ref } from 'vue';
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep';

import $api from '@/api/index';
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token';
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes';
import { getTime } from '@/utils/time'

import { user, menu } from '@/model/index';


export const useUserStore = defineStore('userStore', () => {

  // menu信息 通过路由获取
  const menuList = ref(constantRoute)

  // token
  const token = ref(GET_TOKEN() || '')

  // 请求登录
  const reqLogin = async function (data) {
    const result = await $api.user.reqLogin(data)
    if (result?.data?.code === 200) {
      token.value = result.data.data

      SET_TOKEN(result.data)

      return 'ok'
    } else {
      return Promise.reject(result?.data?.message)
    }
  }

  // 请求用户信息
  const userInfo = ref({})
  const userButtons = ref([])
  const reqUserInfo = async function (data) {
    const result = await $api.user.reqUserInfo()
    if (result?.data?.code === 200) {
      userInfo.value = result.data.data
      userButtons.value = result.data.data.buttons
      // 计算当前用户的异步路由
      const userAsyncRoute = filterUserRoute(cloneDeep(asyncRoute), result.data.data.routes)
      // 整合菜单路由，让菜单组件渲染菜单
      menuList.value = [...constantRoute, ...userAsyncRoute, anyRoute]
      // 动态添加路由
      const routeTmp = [...userAsyncRoute, anyRoute]
      await routeTmp.forEach(route => router.addRoute(route))

      return 'ok'
    } else {
      return Promise.reject(result?.data?.message)
    }
  }

  // 处理异步路由
  const filterUserRoute = (asyncRoute, route) => {
    return asyncRoute.filter(item => {
      if (item.children && item.children.length > 0) {
        // 有子路由的情况
        item.children = filterUserRoute(item.children, route)
        return true
      } else if (route.includes(item.name)) {
        // 没有子路由的情况
        return true
      }
    })
  }

  // 请求退出登录
  const reqLogout = async function () {
    const result = await $api.user.reqLogout()
    if (result?.data?.code === 200) {
      // 清理数据
      userInfo.value = {}
      token.value = ''
      REMOVE_TOKEN()


      return 'ok'
    } else {
      return Promise.reject(result?.data?.message)
    }
  }



  return {
    token, menuList, userInfo, userButtons,
    reqLogin, reqUserInfo, reqLogout,
  }
})